package com.adam.example.aggregation.bucket;

import co.elastic.clients.elasticsearch.ElasticsearchClient;
import co.elastic.clients.elasticsearch._types.aggregations.Aggregate;
import co.elastic.clients.elasticsearch._types.aggregations.Buckets;
import co.elastic.clients.elasticsearch._types.aggregations.IpRangeAggregate;
import co.elastic.clients.elasticsearch._types.aggregations.IpRangeBucket;
import co.elastic.clients.elasticsearch.core.SearchRequest;
import co.elastic.clients.elasticsearch.core.SearchResponse;
import com.adam.example.ElasticsearchClientHolder;
import com.adam.example.util.CollectionStreamUtil;
import com.adam.example.util.JsonUtil;
import com.adam.example.util.OkHttpUtil;
import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.List;
import java.util.Map;

public class OkHttpIpRangeAggregationExample {

    public static void main(String[] args) throws IOException {
        SearchRequest searchRequest = SearchRequest.of(builder -> builder
                        .index("test_ip")
                        .size(0)
                        .aggregations("agg", aggregationBuilder -> aggregationBuilder
                                .ipRange(ipRangeAggregationBuilder -> ipRangeAggregationBuilder
                                        .field("ip")
                                        .ranges(ipRangeAggregationRangeBuilder -> ipRangeAggregationRangeBuilder
                                                .to("10.0.0.5")
                                        )
                                        .ranges(ipRangeAggregationRangeBuilder -> ipRangeAggregationRangeBuilder
                                                .from("10.0.0.5")
                                        )
                                )
                        )
        );
        String requestJson = JsonUtil.searchRequestToJson(searchRequest);
        System.out.println("请求json:" + requestJson);

        String responseJson = OkHttpUtil.postSearch("test_ip", requestJson);
        System.out.println("响应json:" + responseJson);
        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> rMap = objectMapper.readValue(responseJson, new TypeReference<>() {});
        List<Map<String, Object>> bucketList = CollectionStreamUtil.build(rMap)
                .getKey("aggregations").getKey("agg").getKey("buckets").getListMap();
        for(Map<String, Object> bucketMap: bucketList) {
            System.out.println(bucketMap.get("key") + ":" + bucketMap.get("doc_count"));
        }
    }

}
